package com.feng.common;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.jfinal.aop.Interceptor;
import com.jfinal.core.ActionInvocation;
import com.jfinal.core.Controller;
import com.jfinal.log.Log4jLogger;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.render.Render;
import com.jfinal.shiro.SH;

public class AuthInterceptor implements Interceptor{

	public void intercept(ActionInvocation ai) {
		Controller controller = ai.getController();		
		HttpServletRequest request=controller.getRequest();
		
		controller.setAttr("basePath", request.getScheme()+"://" + 
				request.getServerName()+":"+request.getServerPort() + 
					request.getContextPath()+"/");
		
		// 联系我们
		Record intro=Db.findFirst("select * from com_introduce");
		if(intro==null){
			Map<String, String> info = new HashMap<String, String>();
			info.put("title", "联系我们");
			info.put("addr", "上海市长宁区天山路");
			info.put("tel", "136xxxxxxx");
			info.put("num", "021-22554477");
			info.put("email", "304222428@qq.com");
			controller.setAttr("intro", info);
		}else{
			controller.setAttr("intro", intro);
		}
		try {				
			if(SH.isAuth()){			
				controller.setAttr("user", SH.getUser());
				controller.setAttr("isLogin", true);
				controller.setAttr("IMAGE_ROOT_PATH", "");
				
			}
			ai.invoke();	
			
		} catch (Exception e) {	
						
			e.printStackTrace();
			// 统一异常处理
			Log4jLogger.getLogger("error : ").error(controller.getClass().getName(), e);
			
			Render render = controller.getRender();
			if(render == null){
				controller.renderFreeMarker("/WEB-INF/view/common/error.ftl");
			}		
		}
	}

}
